<!-- 点位信息列表信息 -->
<template>
  <div class="q-pa-md bg-white" id="warn-set-site">
    <q-table
      ref="assetTable"
      flat
      class="my-sticky-column-table"
      title="Treats"
      :rows="dataList"
      :columns="columns"
      :filter="filter"
      no-data-label="暂无数据"
      no-results-label="过滤器没有发现任何结果"
      row-key="name"
      :visible-columns="visibleColumns"
      v-model:pagination="pagination"
      hide-pagination
      :loading="loading"
    >
      <!-- 表格的加载状态 -->
        <template v-slot:loading>
          <q-inner-loading showing color="grey" />
        </template>
      <!-- 表格顶部 -->
      <template v-slot:top>
        <div style="width: 230px" class="q-mt-xs q-mr-sm" >
          <q-select dense options-dense outlined v-model="headerSeach" :options="deviceNameOptions" />
        </div>
        <div v-show="headerSeach" style="width: 200px" class="q-mr-sm q-mt-xs">
          <q-input  outlined v-model="queryList[seachContent[headerSeach]]" dense />
        </div>
        <q-btn class="q-mr-sm q-mt-xs borderRadius" unelevated icon="search" padding="8px 8px 7px" color="primary" label="搜索" @click="handlerSearch" />
        <q-btn class="q-mr-sm q-mt-xs borderRadius" unelevated color="primary" padding="8px 8px 7px" label="复位搜索" @click="handleResetSearch" />
        <q-space />
        <q-select
          v-model="visibleColumns"
          multiple
          outlined
          dense
          options-dense
          :display-value="'表头选择'"
          emit-value
          map-options
          :options="columns"
          option-value="name"
          options-cover
          style="min-width: 150px"
          class="q-mt-xs q-mr-sm"
        />
        <q-btn
          flat round dense
          :icon="$q.fullscreen.isActive ? 'fullscreen_exit' : 'fullscreen'"
          @click="toggleFullscreen"
          class="q-mt-xs"
        />
      </template>
      <!-- 无数据提示信息 -->
      <template v-slot:no-data="{ message }">
        <div class="full-width row flex-center text-accent q-gutter-sm">
          <span>
            {{ message }}
          </span>
        </div>
      </template>
      <!-- 表格头部 -->
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
          >
            {{ col.label }}
            <q-icon v-if="col.isSort" class="cursor-pointer" size="18px" :name="pagination.descending?'expand_less':'expand_more'" @click="handlerSort"></q-icon>
          </q-th>
        </q-tr>
      </template>
      <!-- 表格主体 -->
      <template v-slot:body="props">
        <q-tr :props="props" >
          <q-td
            :class="props.row.id === siteId?'click-row':''"
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
            @click="handlerRowSelect(col, props)"
          >
            <span v-if="!col.isImg && col.name!=='btn'">{{ col.value }}</span>
            <span v-if="col.isImg && col.name!=='btn'">
              <img style="height: 28px;" :src="col.value" alt="暂无图片">
            </span>
            <q-btn
              v-if="!col.isImg && col.name==='btn'"
              size="md"
              @click="handlerDetailSensor(props.row)"
              unelevated
              class="q-mr-xs"
              padding="0 10px"
              :class="themeColor.primary === '#00CBED'?'meijia-detail-detail-style':'ebit-detail-style'"
              dense
            >
              详情
            </q-btn>
          </q-td>
        </q-tr>
      </template>
    </q-table>
    <!-- 分页 -->
    <Pagination
      :pagination="pagination"
      :pageSizes="['10条/页','20条/页','30条/页','50条/页']"
      @updatePage="updatePage"
      @updateSizes="updateSizes"
      @handlerRefresh="handlerRefresh"
    />
  </div>

  <!-- 详情 提示框 -->
  <DetailDialog :isShowDetail="isShowDetail" :detailList="detailList" :titleName="'点位信息详情'" @closeDetail="closeDetail" />
</template>

<script>
import { ref } from 'vue'
import DetailDialog from 'src/components/detailDialog/index'
import { featchMonitorSite, detailSiteInfo} from 'src/api/siteMonitor'
import hosts from 'src/utils/host.js'
import Pagination from 'src/components/pagination'
import { mapGetters } from 'vuex';

const labelArr = {
  'id': 'ID',
  'sn': '点位编号',
  'alias_name': '点位名称',
  'type': '点位类型',
  'equip_id_sn': '隶属于资产',
  'dev_id_sn': '关联传感器',
  'img': '点位图片',
  'is_active': '是否激活',
  'modify_time': '修改时间',
  'create_time': '创建时间'
}
export default {
  data () {
    return {
      dataList: [],
      filter: ref(''),

      columns: [
        { name: 'idIndex', required: true, label: 'ID', align: 'center',field: 'idIndex', isSort: true, isImg: false},
        { name: 'img', align: 'center', label: '点位图片', field: 'img', isImg: true },
        { name: 'alias_name', align: 'center', label: '点位名称', field: 'alias_name', isImg: false},
        { name: 'sn', required: true, label: '点位编号', align: 'center',field: 'sn', isImg: false},
        { name: 'btn', align: 'center', label: '操作', field: 'btn',isImg: false},
      ],

      // 表格头部
      headerSeach: ref(),
      deviceNameOptions: ['', '点位名称', '点位编号'],
       // 右侧表头选择
      visibleColumns: ref([]),
      pagination: { // 分页
          sortBy: 'desc', // 列名
          descending: false, // 是否按照降序排序
          page: 1, // 页码（当前显示第几页的数据）
          rowsPerPage: 10, // 每页多少行
          rowsNumber: 10 // 共多少条
      },
      queryList: {
        page: 1,
        page_size: 10,
        ordering: 'id'
      },
      loading: false,
      isShowDetail: false,
      detailList: [],
      seachContent: {
        '点位编号' : 'sn',
        '点位名称' : 'alias_name'
      },
      siteId: null
    }
  },

  components: {
    DetailDialog,
    Pagination
  },
  computed: {
    ...mapGetters(['themeColor'])
  },
  watch: {
  },
  beforeCreate() {
  },
  mounted() {
    this.handleSelect()
    this.feathOranizerList()
  },

  methods: {
    // 刷新
    handlerRefresh() {
      this.handleResetSearch()
    },
    // 切换当前页数
    updatePage(val) {
      if (!val) return
      this.pagination.page = val*1
      this.feathOranizerList()
    },
    // 切换每页的行数
    updateSizes(val) {
      this.pagination.rowsPerPage = parseFloat(val)
      this.feathOranizerList()
    },
    /**
     * 搜索
     */
    handlerSearch() {
      this.feathOranizerList()
    },
    /**
     * 复位搜索
     */
    handleResetSearch() {
      this.pagination = {
        sortBy: 'desc',
        descending: false,
        page: 1,
        rowsPerPage: 10
      }
      this.queryList = {
        page: 1,
        page_size: 10,
        ordering: 'id'
      }
      this.headerSeach = ''
      this.feathOranizerList()
    },
    /**
     * 排序
     */
    handlerSort() {
      this.pagination.descending = !this.pagination.descending
      this.feathOranizerList()
    },
    /**
     * 选中行
     */
    handlerRowSelect(col, props) {
      this.siteId = props.row.id
      this.$store.commit('site/SET_SITE_ID', this.siteId)
    },
    /**
     * 获取资产信息的列表
     */
    feathOranizerList() {
      this.loading = true
      this.queryList.page = this.pagination.page
      this.queryList.page_size = this.pagination.rowsPerPage
      this.queryList.ordering = this.pagination.descending?'-id':'id'
      featchMonitorSite(this.queryList).then(res => {
        const {status, data, totalCounts} = res
        if (status === 200) {
          this.dataList = []
          if (data && data.length > 0) {
            data.forEach((item, index) => {
              // 图片路径
              if (item.img && item.img.indexOf('http://') < 0) {
                if (item.img.split('/')[0] === '') item.img = item.img.substr(1, item.img.length-1)
                item.img = hosts + item.img
              }
              // 处理序号
              if (!this.pagination.descending) {
                item.idIndex = index + 1 + (this.queryList.page - 1) * this.queryList.page_size
              } else {
                item.idIndex = totalCounts - index - (this.queryList.page - 1) * this.queryList.page_size
              }
              this.dataList.push({
                id: item.id,
                idIndex: item.idIndex,
                img: item.img,
                alias_name: item.alias_name,
                sn: item.sn,
              })
            });
          }
          this.pagination.rowsNumber = totalCounts
          this.siteId = this.dataList[0].id
          this.$store.commit('site/SET_SITE_ID', this.dataList[0].id)
        }
        this.loading = false
      }).catch(_ => {
        this.loading = false
      })
    },
    /**
     * 详情
     */
    handlerDetailSensor(val) {
      if (val) {
        detailSiteInfo(val.id).then(res => {
          this.detailList = []
          const {data, status, msg} = res
          if (status === 200) {
            if (data.dev_base_id) {
              this.detailList.push({
                label: 'ID',
                key: data.dev_base_id.id
              })
            }
            this.deepDetailData(data, labelArr)
          } else {
            this.$q.notify({
              type: 'warning',
              message: msg
            })
          }
        })
      }
      this.isShowDetail = true
    },
    // 递归详情数据
    deepDetailData(data, labelArr) {
      if (data) {
        for (let key in data) {
          if (labelArr[key]) {
            if (labelArr[key].indexOf('时间') >= 0) {
              let copyTime = ''
              if (data[key]) copyTime = data[key].substr(0, 10) + ' ' + data[key].substr(11,8)
              this.detailList.push({
                label: labelArr[key],
                key: copyTime
              })
            } else if (labelArr[key].indexOf('点位图片') >= 0) {
              let img = ''
              if (data[key].indexOf(hosts) < 0) {
                if (data[key].split('/')[0] === '') data[key] = data[key].substr(1, data[key].length-1)
                img = hosts + data[key]
              } else {
                img = data[key]
              }
              this.detailList.push({
                label: labelArr[key],
                img: img
              })
            } else {
              this.detailList.push({
                label: labelArr[key],
                key: data[key]
              })
            }
          }
        }
      }
    },
    /**
     * 关闭详情提示框
     */
    closeDetail() {
      this.isShowDetail = false
    },
    /**
     * 处理数据
     */
    handleSelect() {
      this.visibleColumns = []
      this.columns.forEach((item, index) => {
        if (index < 6) {
          this.visibleColumns.push(item.name)
        }
      })
    },
    /**
     * 全屏
     */
    toggleFullscreen() {
      this.$nextTick(_ => {
        const dom = document.getElementById('warn-set-site')
        this.$q.fullscreen.toggle(dom).then(_ => {
        }).catch(error => {
          console.log(error)
        })
      })
    }
  }
}

</script>
<style lang='scss' scoped>
// 固定操作列
.my-sticky-column-table {
  tr:first-child {
    th:last-child {
      background: #fff;
    }
  }
  td {
    &:last-child {
      background: #fff;
    }
  }
  th:last-child, td:last-child {
    position: sticky;
    right: 0;
    z-index: 1;
  }
}
// 弹出的对话框样式
.dialog-form-container {
  ul {
    li {
      height: 42px;
      line-height: 42px;
      white-space: nowrap;
      margin-bottom: 30px;
      >span {
        &:first-child {
          display: inline-block;
          width: 150px;
          margin-right: 5px;
        }
        &:last-child {
          display: inline-block;
          width: 200px;
          >.q-input {
            width: 200px;
          }
        }
      }
    }
  }
}

.click-row {
  background-color: rgba(0,0,0,0.06) !important;
}
</style>
